//
//  YunCangViewController.swift
//  Wmsmobile
//
//  Created by wangshuning on 16/7/19.
//  Copyright © 2016年 Nick xu. All rights reserved.
//

import UIKit

import SVProgressHUD

import MMDrawerController

let CellSpaceMainmenu:CGFloat = KscreenWidth > 400 ? 1/3 : 0.5

class YunCangView: UICollectionView,YunCangViewModelDelegate,UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {
    //MARK: - property
    var viewModel:YunCangViewModel?
    var dataArray:[Array<YunCangModel>]?
    var bgView:UIView?

    //MARK: - life cycle
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        flowLayout.minimumLineSpacing = CellSpaceMainmenu
        flowLayout.minimumInteritemSpacing = CellSpaceMainmenu
        flowLayout.headerReferenceSize = CGSize(width: KscreenWidth, height: 27)
        viewModel = YunCangViewModel()
        viewModel?.delegate = self
        self.register(YunCangViewCellCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        self.register(MainMenuSectionHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
        self.backgroundColor = UIColor.hexStringToUIColor("#dddddd")
        viewModel?.updateData()
        self.dataSource = self
        self.delegate = self
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - delegate
    func updateDatasource(_ array: NSArray?) {
//        if dataArray == nil {
            if let datarr = array{
                self.dataArray = datarr as? [Array<YunCangModel>]
                self.reloadData()
            }else{
                let alertController = UIAlertController(title: "提示", message: "网络连接的有误，是否重新连接", preferredStyle: UIAlertControllerStyle.alert)
                alertController.addAction(UIAlertAction(title: "否", style: UIAlertActionStyle.cancel, handler: nil))
                alertController.addAction(UIAlertAction(title: "是", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
                    let vc = LoginViewController()
                    let window = UIApplication.shared.keyWindow
                    window?.rootViewController = vc
                }))
                self.parentController()?.navigationController?.present(alertController, animated: true, completion: nil)
            }
    }
    //MARK: - collectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.deselectItem(at: indexPath, animated: true)
        if (indexPath as NSIndexPath).row + 1 > self.dataArray![(indexPath as NSIndexPath).section].count{
            return
        }
        let model:YunCangModel = (self.viewModel?.ArrayMenuData[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row])!
        let VCName = (model.FCLASSNAME?.replacingOccurrences(of: ".", with: "_"))! + "Controller"
        if let VCClassTemp = stringClassFromStringOptional(VCName){
            if let VCClass = VCClassTemp as? UITableViewController.Type {
                let vc = VCClass.init()
                self.parentController()?.navigationController?.pushViewController(vc, animated: true)
                return
            }
        }
//        if let dataArrayName = model.FCAPTION{
//            let path = Bundle.main.path(forResource: "controllersData.plist", ofType: nil)
//            if NSDictionary(contentsOfFile:(path)!)![dataArrayName] != nil{
//                let vc = ContainerPickController(info: NSDictionary(contentsOfFile:(path)!)![dataArrayName] , model: model)
//                vc.title = dataArrayName
//                self.parentController()?.navigationController?.pushViewController(vc, animated: true)
//            }
//        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let column:CGFloat = userInfo?.fontLevel == .large ? 3 : 4
        let columnd:CGFloat = column - 1 //代表列数 -1
        let width:CGFloat = ((KscreenWidth - columnd * CellSpaceMainmenu) - (KscreenWidth - columnd * CellSpaceMainmenu).truncatingRemainder(dividingBy: (CellSpaceMainmenu * column))) / column
        if (indexPath as NSIndexPath).row % Int(column) == 2 {
            let newWidth = collectionView.contentSize.width - columnd * (width + CellSpaceMainmenu)
            return CGSize(width: newWidth, height: width)
        }
        return CGSize(width: width, height: width)
    }
}
//MARK: - datasource
extension YunCangView: UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
       return self.dataArray?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let rows = self.dataArray?[section].count {
            let column = userInfo?.fontLevel == .large ? 3 : 4
            if rows % column == 0{
                return rows
            }
            return rows + (column - rows % column)
        }
        return self.dataArray?[section].count ?? 0
    }
     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model:YunCangModel? = (self.dataArray?[(indexPath as NSIndexPath).section].count)!  < (indexPath as NSIndexPath).row + 1 ? nil : (self.dataArray?[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).item])
        let cell:YunCangViewCellCollectionViewCell = (collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? YunCangViewCellCollectionViewCell)!
        cell.model = model
        return cell
    }
//    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//        
//    }
// override func collectionView(collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//        
//        let model:YunCangModel? = (self.dataArray?[(indexPath as NSIndexPath).section].count)!  < (indexPath as NSIndexPath).row + 1 ? nil : (self.dataArray?[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).item])
//        let cell:YunCangViewCellCollectionViewCell = (collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? YunCangViewCellCollectionViewCell)!
//            cell.model = model
//        return cell
//    }

 @objc(collectionView:viewForSupplementaryElementOfKind:atIndexPath:) func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let model = self.viewModel?.ArrayMenuHeaderData[(indexPath as NSIndexPath).section]
        let header:MainMenuSectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! MainMenuSectionHeaderView
        header.model = model
        return header
    }
    @objc(collectionView:layout:insetForSectionAtIndex:) func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        //        let remind:CGFloat = userInfo?.fontLevel == .large ? 1.5 : 2
        //        switch (KscreenWidth - remind + 0.5) % remind {
        //        case 0:
        //            return UIEdgeInsetsMake(0.5, 0, 0.5, 0)
        //        case 0.5:
        //            return UIEdgeInsetsMake(0.5, 0.5, 0.5, 0)
        //        case 1:
        //            return UIEdgeInsetsMake(0.5, 0.5, 0.5, 0.5)
        //        case 1.5:
        //            return UIEdgeInsetsMake(0.5, 1, 0.5, 0.5)
        //        default:
        return UIEdgeInsetsMake(CellSpaceMainmenu, 0, CellSpaceMainmenu, 0)
        //        }
        
    }
}
